<template>
	<view>
		<cu-custom bgColor="theme-bg-color" :isBack="true">
			<block slot="backText"><text>返回</text></block>
			<block slot="content"><text> 我的人脸 </text></block>
		</cu-custom>
		<view>
			<view class="text-red margin-xs">提示</view>
			<view class="margin-xs">请上传至少5张人脸</view>
			<view class="margin-xs">上传的人脸越多识别的效果更加明显</view>
			<view class="margin-xs">请不要在比较昏暗的环境进行上传头像</view>
			<view class="cu-list grid  col-3  padding-xs">
				<template v-for="(item,index) in Faces">
					<view class="cu-item" :class="false?'arrow':''" @click="Join('userinfo-edit')">
						<view class="content flex flex-direction justify-center align-center">
							<image :src="item.FaceImageUrl" style="width:200upx;height:200upx;border-radius:10upx;" mode="aspectFill">
							</image>
							<text class=" text-gray " style="padding-left:10upx">第{{index+1}}人脸</text>
							<button style="width:80%" class="cu-btn block bg-red margin-tb-sm  xs" @click="DelFace(item)">删除人脸</button>
						</view>
					</view>
				</template>



			</view>

		</view>
		<view class="fixed-bottom">
			<view class="">
				<button class="cu-btn block theme-bg-color margin-tb-sm lg" @click="Upload()">上传人脸</button>

			</view>

		</view>


	</view>
</template>

<script>
	import store from "@/store";
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				Faces: [],

			}
		},
		computed: {
			...mapGetters(["userInfo"]),
		},
		onLoad() {
			this.GetMyFaceList();
		},
		onShow() {
			if (this.$comm.CheckToken()) {

			}
		},
		methods: {
			async UploadMook() {

				let updateResult = await this.$http.Upload(file);
				console.log("文件", updateResult)
				//this.Updaface(this.mook)
			},
			async GetMyFaceList() {
				let {
					Data: {
						Items
					},
					Success,
				} = await this.$http.PostAsync("/UserFace/List", {
					UserId: this.userInfo.Id,
				});
				this.Faces = Items
			},
			async DelFace(item) {
				let confirm = await this.$comm.ShowModal("你确定要删除人脸吗?");
				
				if (confirm == false) {
					await this.$comm.ShowToast("用户放弃操作");
					return;
				}
				let {
					Data: {
						Items
					},
					Success,
				} = await this.$http.PostAsync("/Face/UserFaceTokenDel", {
					UserId: item.UserId,
					FaceToken: item.FaceToken,
				});
				await this.$http.PostAsync("/UserFace/Delete", {
					Id: item.Id
				});
				await this.GetMyFaceList();
			},
			async Updaface(base64, path) {

				try {

					uni.showLoading({
						title: "识别人脸结果中",
						icon: "none"
					})
					let {
						Data: ImageUrls
					} = await this.$http.Upload(path);
					let imgUrl = ImageUrls[0].Url;

					let {
						Data: FaceToken,
						Success,
					} = await this.$http.PostAsync("/Face/UploadFace", {
						UserId: this.userInfo.Id,
						Image: base64
					});
					console.log("okzz")
					console.log(Success)
					if (Success) {
						await this.$http.PostAsync("/UserFace/CreateOrEdit", {
							UserId: this.userInfo.Id,
							FaceImageUrl: imgUrl,
							FaceToken: FaceToken
						});
						uni.hideLoading();
						this.$comm.showToast("上传人脸成功");


					} else {
						uni.hideLoading();
						this.$comm.showToast("上传人脸失败");
					}
				} catch {
					uni.hideLoading();
				} finally {
					this.GetMyFaceList();
				}


			},
			Upload() {
				// uni.navigateTo({
				// 	url: "/pages/user-center/UpdateFace",
				// 	events: {
				// 		data: async (path) => {

				// 			let bs64 = await this.$comm.TempToBase64(path);
				// 			console.log(bs64.data, path)
				// 			await this.Updaface(bs64.data, path)

				// 		}
				// 	}
				// })
				this.uploadImage();
			},
				async TempToBase64(tempFiles) {
						// #ifdef H5
			
						return new Promise((resolve, reject) => {
							const reader = new FileReader();
							// 如果 tempFiles 是 File 对象
							if (tempFiles instanceof File) {
								reader.readAsDataURL(tempFiles);
							}
							// 如果 tempFiles 是 URL 字符串
							else {
								fetch(tempFiles)
									.then(response => response.blob())
									.then(blob => reader.readAsDataURL(blob))
									.catch(err => reject(err));
							}
			
							reader.onload = () => {
								const base64 = reader.result.split(',')[1];
								resolve({ data: base64 });
							};
							reader.onerror = error => reject(error);
						});
			
						// #endif
						// #ifdef MP-WEIXIN || MP-QQ
						// 非 H5 平台使用原有逻辑
						return new Promise((resolve, reject) => {
							uni.getFileSystemManager().readFile({
								filePath: tempFiles,
								encoding: 'base64',
								success(dataRes) {
									resolve(dataRes);
								},
								fail(err) {
									reject(err);
									console.error('读取文件失败：' + err.message);
								}
							});
						});
						// #endif
					},
					async uploadImage() {
						uni.chooseImage({
							count: 1,
							success: async (res) => {
								const tempFilePath = res.tempFilePaths[0];
								let bs64 = await this.TempToBase64(tempFilePath);
								console.log(bs64)
								await this.Updaface(bs64.data,tempFilePath)
							
							}
						});
					}

		}
	}
</script>

<style>
	.fixed-bottom {
		position: fixed;
		width: 100%;

		padding: 20upx;
		bottom: 0;
		left: 0;
		z-index: 9999;
		background-color: white;
	}
</style>